package lab.three.positioning;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class PositionService extends Service {

	private int m_startMode; // Indicates how to behave if the service is killed.
	private IBinder m_binder; // Interface for clients that bind.
	private boolean m_AllowRebind; // Indicates whether onRebind should be used.
	
	@Override
	public void onCreate() 
	{
		// The service is being created.
		Log.d("debug-event", "PositionService onCreate");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) 
	{
		// The service is starting, due to a call to startService().
		Log.d("debug-event", "PositionService onStartCommand");
		
		// Acquire a reference to the system Location Manager.
		LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
		
		// Define a listener that response to location updates.
		LocationListener locationListener = new LocationListener() 
		{
			public void onLocationChanged(Location location) 
			{
				// Called when a new location is found by the network location provider.
				Log.d("debug-event", "locationListener onLocationChanged");

				// Make use of the new location.
				sendLocationData(location);
			}
			
			public void onStatusChanged(String provider, int status, Bundle extras) 
			{
				// Called when the status changes.
				Log.d("debug-event", "locationListener onStatusChanged");
			}
			
			public void onProviderEnabled(String provider) 
			{
				// Called to check if provider is enabled.
				Log.d("debug-event", "locationListener onProviderEnabled");
			}
			
			public void onProviderDisabled(String provider) 
			{
				// Called to check if the provider is disabled.
				Log.d("debug-event", "locationListener onProviderDisabled");
			}
		};
		
		// Register the listener with the Location Manager to receive location updates.
		try
		{
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			Log.d("debug-event", "PositionService onStartCommand after location has been requested");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return m_startMode;
	}
	
	public void sendLocationData(Location loc)
	{
		Log.d("debug-event", "PositionService sendLocationData");
		
		double latitude = loc.getLatitude();
		double longitude = loc.getLongitude();
		
		
		String toastText = "Latitude: " + latitude + "\nLongitude: " + longitude;
		
		final String latString = "" + latitude;
		final String longString = "" + longitude;
		final String accString = "" + loc.getAccuracy();

		new Thread(new Runnable() {
			
			public void run() 
			{
				try
				{
					Log.d("debug-event", "Inside worker thread.");
					
					String urlString = "http://homepage.lnu.se/staff/tblma/race/setpos.php";
					URI url = new URI(urlString);
					
					// Create a new HttpClient and Post Header.
					HttpClient client = new DefaultHttpClient();
					HttpPost post = new HttpPost(url);
					
					// Create data to be sent via HTTP.
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
					nameValuePairs.add(new BasicNameValuePair("lat", latString));
					nameValuePairs.add(new BasicNameValuePair("lon", longString));
					nameValuePairs.add(new BasicNameValuePair("acc", accString));

					post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					
					// Execute HTTP Post Request.
					@SuppressWarnings("unused")
					HttpResponse response = client.execute(post);
					
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				
			}
		}).start();
				
		Context context = getApplicationContext();
		
		Toast toast = Toast.makeText(context, toastText, 5000);
		toast.show();
	}
	
	@Override
	public void onDestroy() 
	{
		// The service is no longer used and is being destroyed.
		Log.d("debug-event", "PositionService onDestroy");
	}
	
	@Override
	public IBinder onBind(Intent intent) 
	{
		// A client is binding to the service with bindService().
		Log.d("debug-event", "PositionService onBind");
		
		return m_binder;
	}
	
	@Override
	public boolean onUnbind(Intent intent) 
	{
		// All clients have unbound with unbindService().
		Log.d("debug-event", "PositionService onUnbind");
		
		return m_AllowRebind;
	}
	
	@Override
	public void onRebind(Intent intent) 
	{
		// A client is binding to the service with bindService(),
		// after onUnbind() has already been called.
		Log.d("debug-event", "PositionService onRebind");
	}
}
